package com.young.coderule.service.impl;

import com.young.coderule.common.redis.RedisSerializerUtil;
import com.young.coderule.entity.ComCodeRuleNumber;
import com.young.coderule.service.CodeRuleCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Arrays;
import java.util.Collections;

/**
 * @DESCRIPTION: 基于redis的缓存，存储最大号信息
 * @USER: Young
 * @DATE: 2022/7/31 10:25
 */
public class CodeRuleRedisCacheService implements CodeRuleCacheService {

    private static final String CODERULE_CACHEMAP = "CODERULE_CACHEMAP";

    private static final RedisScript<Object> SCRIPT_GET = new DefaultRedisScript("return redis.call('hget', KEYS[1], KEYS[2]) ", Object.class);
    private static final RedisScript<Long> SCRIPT_PUT = new DefaultRedisScript("return redis.call('hset', KEYS[1], KEYS[2], ARGV[1]) ", Long.class);


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ComCodeRuleNumber getCodeRuleNumber(String code) {

//        return (ComCodeRuleNumber) redisTemplate.execute(SCRIPT_GET,RedisSerializerUtil.redisSerializerString,RedisSerializerUtil.fastJson2JsonRedisSerializer, Arrays.asList(CODERULE_CACHEMAP, code));
        setSerializer();
        return (ComCodeRuleNumber)redisTemplate.boundHashOps(CODERULE_CACHEMAP).get(code);
    }

    @Override
    public void putCodeRuleNumber(String code, ComCodeRuleNumber codeRuleNumber) {
//        redisTemplate.execute(SCRIPT_PUT,RedisSerializerUtil.fastJson2JsonRedisSerializer,RedisSerializerUtil.fastJson2JsonRedisSerializer, Arrays.asList(CODERULE_CACHEMAP, code), codeRuleNumber);
        setSerializer();
        redisTemplate.boundHashOps(CODERULE_CACHEMAP).put(code, codeRuleNumber);
    }

    void setSerializer(){
        redisTemplate.setKeySerializer(RedisSerializerUtil.redisSerializerString);
        redisTemplate.setHashKeySerializer(RedisSerializerUtil.redisSerializerString);
        redisTemplate.setValueSerializer(RedisSerializerUtil.fastJson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(RedisSerializerUtil.fastJson2JsonRedisSerializer);

    }
}
